<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--表单组件-->
      <el-form
        ref="form"
        class="formClass"
        :model="form"
        :rules="rules"
        size="small"
        label-width="120px"
      >
        <div class="fieldset">
          <label class="group">基本信息</label>
          <el-form-item label="编码" class="itemRow" prop="code">
            <el-input v-model="form.code" class="filedWidth" />
          </el-form-item>
          <el-form-item label="名称" class="itemRow">
            <el-input v-model="form.name" class="filedWidth" />
          </el-form-item>

          <el-form-item label="源数据源" class="itemRow" prop="dsSource">
            <el-select
              v-model="form.dsSource"
              class="filedWidth"
              placeholder="请选择"
              @change="
                val => {
                  getDsSourceTables(val, false);
                }
              "
            >
              <el-option
                v-for="item in sourceDsSourceArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="源表名"
            class="itemRow formSearchFiled"
            prop="sourceTable"
          >
            <!-- <div class="searchFiled"> -->
            <el-input
              ref="sourceTable"
              v-model="form.sourceTable"
              class="checkFiledWidth"
            />
            <span
              class="el-icon-zoom-in searchIcon"
              @click="openSelectSourceTable()"
            />
            <!-- </div> -->
          </el-form-item>
          <el-form-item label="目标数据源" class="itemRow" prop="dsTarget">
            <el-select
              v-model="form.dsTarget"
              class="filedWidth"
              placeholder="请选择"
              @change="
                val => {
                  getDsTargetTables(val, false);
                }
              "
            >
              <el-option
                v-for="item in sourceDsSourceArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="目标表名"
            class="itemRow formSearchFiled"
            prop="targetTable"
          >
            <!-- <div class="searchFiled"> -->
            <el-input
              ref="targetTable"
              v-model="form.targetTable"
              class="checkFiledWidth"
            />
            <span
              class="el-icon-zoom-in searchIcon"
              @click="openSelectTargetTable()"
            />
            <!-- </div> -->
          </el-form-item>
          <el-form-item label="源表主键" class="itemRow" prop="sourcePk">
            <el-input v-model="form.sourcePk" class="filedWidth" />
          </el-form-item>
          <el-form-item label="目标表主键" class="itemRow" prop="targetPk">
            <el-input v-model="form.targetPk" class="filedWidth" />
          </el-form-item>
          <el-form-item
            label="同步表结构"
            class="itemRow"
            style="display:none"
            prop="syncTableDdl"
          >
            <el-radio-group v-model="form.syncTableDdl" class="filedWidth">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="记录日志"
            class="itemRow"
            style="display:none"
            prop="recordLog"
          >
            <el-radio-group v-model="form.recordLog" class="filedWidth">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="启用" class="itemRow" prop="delFlag">
            <el-radio-group v-model="form.delFlag" class="filedWidth">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所属项目" class="itemRow" prop="projectName">
            <el-select
              v-model="form.projectName"
              class="filedWidth"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dict.project_name"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" class="itemLongRow" prop="memo">
            <el-input
              v-model="form.memo"
              type="textarea"
              class="filedWidthLong"
            />
          </el-form-item>
          <el-form-item label="自动同步字段" class="itemRow" prop="isItSync">
            <el-radio-group v-model="form.isItSync" class="filedWidth">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="fieldset">
          <label class="group">扩展信息</label>
          <el-form-item label="查询语句" class="itemLongRow" prop="querySql">
            <el-input
              v-model="form.querySql"
              type="textarea"
              rows="4"
              class="filedWidthLong"
            />
          </el-form-item>
          <el-form-item
            label="行数据处理类"
            class="itemLongRow"
            prop="extClass"
          >
            <el-input v-model="form.extClass" class="filedWidthLong" />
          </el-form-item>
          <el-form-item label="扩展类" class="itemLongRow" prop="handlerClass">
            <el-input v-model="form.handlerClass" class="filedWidthLong" />
          </el-form-item>
          <el-form-item
            label="扩展属性"
            class="itemLongRow"
            style="display:none"
            prop="extJson"
          >
            <el-input v-model="form.extJson" class="filedWidthLong" />
          </el-form-item>
          <el-form-item label="增量字段" class="itemRow" prop="fdIncr">
            <el-input v-model="form.fdIncr" class="filedWidth" />
          </el-form-item>
          <el-form-item label="增量值" class="itemRow" prop="incrValue">
            <el-input v-model="form.incrValue" class="filedWidth" />
          </el-form-item>
          <el-form-item
            label="上次同步时间"
            class="itemRow"
            prop="lastSyncTime"
          >
            <el-input v-model="form.lastSyncTime" disabled class="filedWidth" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="loading === 2"
          type="primary"
          @click="submit"
        >保存</el-button>
        <el-button
          v-if="edit"
          type="warning"
          @click="configFiled"
        >配置字段</el-button>
      </div>
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="configDialog"
        title="配置字段"
        width="650px"
      >
        <el-table :data="configData" border style="width: 100%">
          <el-table-column prop="date" label="源数据源表字段" width="300" />
          <el-table-column prop="name" label="目标数据源字段" width="300" />
        </el-table>
      </el-dialog>

      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="checkSourceTableShow"
        title="选择源数据源的表"
        width="820px"
      >
        <div class="filterInput">
          <el-input v-model="fieldFilter" placeholder="请输入筛选条件" />
        </div>
        <div
          v-if="checkFilter(fieldFilter, sourceTableArr).length > 0"
          class="check_ul"
        >
          <span
            v-for="(item, index) in checkFilter(fieldFilter, sourceTableArr)"
            :key="index"
            :class="item.checked ? 'li_checked' : ''"
            class="check_li"
            @click="selectSourceTable(index, item.label, item.value)"
          >{{ item.value }}</span>
        </div>
        <div v-else class="check_ul">暂无数据</div>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="text"
            @click="checkSourceTableShow = false"
          >取消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="checkTargetTableShow"
        title="选择目标数据源的表"
        width="820px"
      >
        <div class="filterInput">
          <el-input v-model="fieldFilter" placeholder="请输入筛选条件" />
        </div>
        <div
          v-if="checkFilter(fieldFilter, targetTableArr).length > 0"
          class="check_ul"
        >
          <span
            v-for="(item, index) in checkFilter(fieldFilter, targetTableArr)"
            :key="index"
            :class="item.checked ? 'li_checked' : ''"
            class="check_li"
            @click="selectTargetTable(index, item.label, item.value)"
          >{{ item.value }}</span>
        </div>
        <div v-else class="check_ul">暂无数据</div>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="text"
            @click="checkTargetTableShow = false"
          >取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
/* eslint-disable */

import crudMigDefMain from "@/api/migrate/migDefMain";
import {
  getOrginSource,
  getTables,
  doMigrate
} from "@/api/migrate/coustomFunction";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import crudOperation from "@crud/CRUD.operation";
import customOperation from "@crud/customOperation";
import pagination from "@crud/Pagination";

import qs from "qs";
const defaultForm = {
  id: "",
  name: "",
  sourceTable: "",
  targetTable: "",
  dsSource: "",
  dsTarget: "",
  extClass: "",
  sourcePk: "",
  targetPk: "",
  extJson: "",
  fdIncr: "",
  incrValue: "",
  querySql: "",
  lastSyncTime: "",
  syncTableDdl: "",
  fdTitle: "",
  fdEmergency: "",
  fdCode: "",
  handlerClass: "",
  recordLog: "",
  isItSync: "",
  projectName: "",
  delFlag: "",
  createTime: "",
  updateTime: "",
  memo: ""
};
export default {
  name: "MigDefAdd",
  components: { pagination, crudOperation, customOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    const formData = CRUD({
      title: "迁移数据定义",
      url: "api/migDefMain",
      sort: "id,desc",
      crudMethod: { ...crudMigDefMain }
    });
    return formData;
  },
  // 设置数据字典
  dicts: ["project_name"],
  watch: {
    form: {
      deep: true,
      handler(val) {
        const syncTableDdl = val.syncTableDdl ? ~~val.syncTableDdl : 2;
        const recordLog = val.recordLog ? val.recordLog : 2;
        const delFlag = val.delFlag ? val.delFlag : 2;
        val = {
          ...val,
          syncTableDdl: syncTableDdl,
          recordLog: recordLog,
          delFlag: delFlag
        };
      }
    }
  },
  data() {
    return {
      loading: 0,
      edit: false,
      targetDialog: false,
      width: 270,
      fieldFilter: "",
      sourceDsSourceArr: [], //数据源的列表
      sourceTableArr: [], //源数据源对应表
      targetTableArr: [], //目标数据源对应表
      dialogArr: [],
      originArr: [],
      configData: [],
      checkSourceTableShow: false, //是否显示选择原始表的弹框
      checkTargetTableShow: false, //是否显示显示目标表的弹框
      configDialog: false,
      permission: {
        add: ["admin", "migDefMain:add"],
        edit: ["admin", "migDefMain:edit"],
        del: ["admin", "migDefMain:del"],
        config: true
      },
      permissionRow: {
        edit: ["admin", "migDefMain:edit"],
        del: ["migDefMain:del"],
        config: true
      },
      rules: {
        id: [{ required: true, message: "编码不能为空", trigger: "blur" }],
        dsSource: [
          { required: true, message: "源数据源不能为空", trigger: "blur" }
        ],
        sourceTable: [
          { required: true, message: "源表不能为空", trigger: "blur" }
        ],
        dsTarget: [
          { required: true, message: "目标数据源不能为空", trigger: "blur" }
        ],
        targetTable: [
          { required: true, message: "目标表名不能为空", trigger: "blur" }
        ],
        sourcePk: [
          { required: true, message: "源表主键不能为空", trigger: "blur" }
        ],
        targetPk: [
          { required: true, message: "目标表名主键不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return false;
    },
    checkFilter(val, arr) {
      let result = arr;
      if (val) {
        result = arr.filter(i => i.value.includes(val));
      }
      return result;
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = 2;
        this.edit ? this.customEdit() : this.customAdd();
      });
    },
    configFiled() {
      const data = this.form;
      const query = {
        id: data.id,
        dsName: data.dsTarget,
        tableName: data.targetTable,
        fieldName: data.dsSource,
        table: data.sourceTable,
        PK_FIELD: "id"
      };
      this.$router.push({
        path: "/migDefItem",
        query
      });
    },
    /**
     * 执行自定义添加
     */
    customAdd() {
      console.log("新增");
      this.crud.crudMethod
        .add(this.form)
        .then((res = {}) => {
          this.loading = 0;
          if (res.RTN_CODE && res.RTN_CODE == "ERROR") {
            this.crud.notify(res.MSG, CRUD.NOTIFICATION_TYPE.ERROR);
          } else {
            this.edit = true;
            this.crud.addSuccessNotify();
            this.form.id = res.id;
          }
        })
        .catch(e => {
          this.loading = 0;
          console.error(e);
        });
    },
    /**
     * 执行自定义编辑
     */
    customEdit() {
      console.log("编辑");
      this.crud.crudMethod
        .edit(this.form)
        .then(() => {
          this.loading = 0;
          this.crud.editSuccessNotify();
        })
        .catch(e => {
          this.loading = 0;
          console.error(e);
        });
    },
    getOrgin() {
      //数据源的列表
      getOrginSource().then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.name,
              value: i.name
            });
          });
          this.sourceDsSourceArr = arr;
        }
      });
    },
    getDsSourceTables(val, changeFlag) {
      //获取源数据源的表
      this.sourceTableArr = [];
      if (changeFlag != false) {
        this.form = {
          ...this.form,
          sourceTable: ""
        };
      }
      let params = {
        dsName: val
      };
      getTables(params).then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.description,
              value: i.name
            });
          });
          this.sourceTableArr = arr;
        }
      });
    },
    getDsTargetTables(val, changeFlag) {
      //获取目标数据源的表
      this.targetTableArr = [];
      if (changeFlag != false) {
        //changeFlag为false的时候，不改变页面上的值
        this.form = {
          ...this.form,
          targetTable: ""
        };
      }

      let params = {
        dsName: val
      };
      getTables(params).then(res => {
        if (res && res.content) {
          let data = res.content;
          let arr = [];
          data.map(i => {
            arr.push({
              label: i.description,
              value: i.name
            });
          });
          this.targetTableArr = arr;
        }
      });
    },

    selectSourceTable(index, label, value) {
      //选择原始表
      // this.form.sourceTable = value;
      this.$set(this.form, "sourceTable", value);
      this.checkSourceTableShow = false;
      this.fieldFilter = "";
      this.$refs.sourceTable.focus();
    },

    selectTargetTable(index, label, value) {
      // 选择目标表
      // this.form.targetTable = value;
      this.$set(this.form, "targetTable", value);
      this.checkTargetTableShow = false;
      this.fieldFilter = "";
      this.$refs.targetTable.focus();
    },

    openSelectSourceTable() {
      //打开选择原表
      if (this.sourceTableArr.length == 0) {
        this.getDsSourceTables(this.form.dsSource, false);
      }
      this.fieldFilter = "";
      this.checkSourceTableShow = true;
    },

    openSelectTargetTable() {
      this.fieldFilter = "";
      if (this.targetTableArr.length == 0) {
        this.getDsTargetTables(this.form.dsTarget, false);
      }
      this.checkTargetTableShow = true;
    }
  },
  created() {
    this.getOrgin();
    const query = this.$route.query;
    this.form = query;
    this.edit = query.queryEdit;
    if (this.form.id) {
      this.edit = true;
      //byid请求详情
      let id = this.form.id;
      if (id) {
        var params = { id };
        crudMigDefMain
          .byid(params)
          .then(res => {
            Object.assign(this.form, res);
          })
          .catch(e => {
            console.log(e.message);
            loading.close();
          });
      }
    }
  }
};
</script>

<style scoped>
.filterInput {
  width: 50%;
  margin-bottom: 15px;
}
</style>
